package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ramos.kuaixiao.MyView.SignDialog;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;


public class TodaySignActivity extends BaseAllTabActivity implements View.OnClickListener {
    private final static String TAG = "TodaySignActivity";
    TextView tv_aboutus;
    TextView tv_distance;
    TextView tv_store_address;
    TextView tv_store_address_error;
    LinearLayout title_reback;
    Button btn_sign_in;
    Button btn_sign_out;
    Customer mCustomer;
    CommonLoading loading;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    public final static int UPLOAD_SUCCESS1 = 200;
    public final static int UPLOAD_FAIL1 = 201;
    SignDialog builder;

    private RelativeLayout re_home_shop;
    private RelativeLayout re_home_order;
    private RelativeLayout re_home_task;
    private RelativeLayout re_home_my;
    private TextView tv_home_shop;
    private TextView tv_home_order;
    private TextView tv_home_task;
    private TextView tv_home_my;
    private ImageView ib_home_shop;
    private ImageView ib_home_order;
    private ImageView ib_home_task;
    private ImageView ib_home_my;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_today_sign_in);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        tv_aboutus = (TextView) findViewById(R.id.title_text);
        tv_aboutus.setText("今日签到");
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);
        mCustomer = (Customer) getIntent().getExtras().get("customer");
        tv_distance = (TextView) findViewById(R.id.tv_distance);
        if (!StringUtil.isEmpty(mCustomer.getDistance())) {
            tv_distance.setText(mCustomer.getDistance()+"km");
        }
        tv_store_address = (TextView) findViewById(R.id.tv_store_address);
        tv_store_address.setText(mCustomer.getAddress());
        btn_sign_in = (Button) findViewById(R.id.btn_sign_in);
        btn_sign_in.setOnClickListener(this);
        btn_sign_out = (Button) findViewById(R.id.btn_sign_out);
        btn_sign_out.setOnClickListener(this);
        tv_store_address_error = (TextView) findViewById(R.id.tv_store_address_error);
        tv_store_address_error.setOnClickListener(this);
        initTabView();
    }

    private void initTabView() {
        re_home_shop = (RelativeLayout) findViewById(R.id.re_home_shop);
        re_home_order = (RelativeLayout) findViewById(R.id.re_home_order);
        re_home_task = (RelativeLayout) findViewById(R.id.re_home_task);
        re_home_my = (RelativeLayout) findViewById(R.id.re_home_my);
        re_home_shop.setOnClickListener(this);
        re_home_order.setOnClickListener(this);
        re_home_task.setOnClickListener(this);
        re_home_my.setOnClickListener(this);

        ib_home_shop = ((ImageView) findViewById(R.id.ib_home_shop));
        ib_home_order = ((ImageView) findViewById(R.id.ib_home_order));
        ib_home_task = ((ImageView) findViewById(R.id.ib_home_task));
        ib_home_my = ((ImageView) findViewById(R.id.ib_home_my));

        tv_home_shop = ((TextView) findViewById(R.id.tv_home_shop));
        tv_home_order = ((TextView) findViewById(R.id.tv_home_order));
        tv_home_task = ((TextView) findViewById(R.id.tv_home_task));
        tv_home_my = ((TextView) findViewById(R.id.tv_home_my));

        ib_home_shop.setImageResource(R.drawable.tab_infomation_clk);
        tv_home_shop.setTextColor(getResources().getColor(R.color.title));

        ib_home_order.setImageResource(R.drawable.tab_schedule);
        tv_home_order.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_task.setImageResource(R.drawable.tab_service);
        tv_home_task.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

        ib_home_my.setImageResource(R.drawable.tab_contacts);
        tv_home_my.setTextColor(getResources().getColor(R.color.bottom_tab_unselected));

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
                break;
            case R.id.btn_sign_in:
                //getTask(1);
                showSignDialog(1);
                break;
            case R.id.btn_sign_out:
                showSignDialog(2);
                break;
            case R.id.re_home_shop:
                showMain(1);
                break;
            case R.id.re_home_order:
                showMain(2);
                break;
            case R.id.re_home_task:
                showMain(3);
                break;
            case R.id.re_home_my:
                showMain(4);
                break;
            case R.id.tv_store_address_error:
                Intent intent = new Intent(this, ErrorAddressActivity.class);
                intent.putExtra("customer", mCustomer);
                startActivity(intent);
                break;
        }
    }

    private void showSignDialog(int i) {
        //getTask(i);
        if (StringUtil.isEmpty(mCustomer.getLat()) || StringUtil.isEmpty(mCustomer.getLon())) {
            if (i == 1) {
                ToastUtils.show("无法获取商店位置，请提交照片");
                builder = new SignDialog(this);
                builder.setUpdateCarListener(new SignDialog.UpdateCarListener() {
                    @Override
                    public void update() {
                        builder.showImage();
                    }
                });
                builder.setNoOnclickListener(new SignDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        builder.dismiss();
                    }
                });
                builder.setYesOnclickListener(new SignDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        sendAddress(builder.mAddress, builder.mImage);
                        builder.dismiss();
                    }
                });
                builder.show();

            } else {
                ToastUtils.show("无法获取商店位置");
            }
        } else {
            getTask(i);
        }
    }

    private void sendAddress(String address, File image) {
        try {
            if (StringUtil.isEmpty(address)) {
                ToastUtils.show("上传地址不能为空");
                return;
            }
            if (image == null) {
                ToastUtils.show("上传图片不能为空");
                return;
            }
            String url = NetUtils.ADDRESS_CORRECT;
            loading = new CommonLoading(this);
            loading.setLoadText("上传图片中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            // 创建请求参数的封装的对象
            RequestParams params = new RequestParams();
            /*if(StringUtil.isEmpty(mCustomer.getHouseId())){
                params.put("qid", mCustomer.getQid());
            } else {
                params.put("qid", mCustomer.getHouseId());
            }*/
            params.put("cid", mCustomer.getId());
            params.put("csId", mCustomer.getHouseId());
            params.put("dealer", mCustomer.getDealer());
            params.put("lon", Double.valueOf(SharedPreference.getPreferString("longitude")));
            params.put("lat", Double.valueOf(SharedPreference.getPreferString("latitude")));
            params.put("address", address);
            params.put("image", image);
            Log.d(TAG, "getTask " + url);
            Log.d(TAG, "getTask " + params.toString());
            // 执行post方法
            client.post(url, params, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    loading.dismiss();
                    Log.d(TAG, "login " + new String(responseBody));
                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(new String(responseBody));
                    try {
                        if (jsonObject.getInteger("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS1, jsonObject.getString("msg"));
                        } else {
                            sendMessagea(UPLOAD_FAIL1, jsonObject.getString("msg"));
                        }
                    } catch (Exception e) {
                        sendMessagea(UPLOAD_FAIL1, "上传异常");
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL1, "上传异常");
                    error.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            sendMessagea(UPLOAD_FAIL1, "上传异常");
            e.printStackTrace();
        }
    }

    private void getTask(int type) {
        try {
            String url = NetUtils.TODAY_SIGN;
            loading = new CommonLoading(this);
            loading.setLoadText("签到中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            // 创建请求参数的封装的对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId", SharedPreference.getPreferString("id"));
            jsonObject.put("sales", SharedPreference.getPreferString("id"));
            jsonObject.put("lon", Double.valueOf(SharedPreference.getPreferString("longitude")));
            jsonObject.put("lat", Double.valueOf(SharedPreference.getPreferString("latitude")));
            jsonObject.put("time", Double.valueOf(SharedPreference.getPreferString("time")));
            jsonObject.put("type", type);
            Log.d(TAG, "getTask " + url);
            Log.d(TAG, "getTask " + jsonObject.toString());
            ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            stringEntity.setContentType("application/json");
            // 执行post方法
            client.post(this, url, stringEntity, "application/json", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
                    loading.dismiss();
                    Log.d(TAG, "login " + responseBody.toString());
                    try {
                        if (responseBody.getInt("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS, responseBody.getString("msg"));
                        } else {
                            sendMessagea(UPLOAD_FAIL, responseBody.getString("msg"));
                        }
                    } catch (JSONException e) {
                        sendMessagea(UPLOAD_FAIL, "签到异常");
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL, "签到异常");
                    throwable.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            sendMessagea(UPLOAD_FAIL, "签到异常");
            e.printStackTrace();
        }
        loading.dismiss();
        sendMessagea(UPLOAD_FAIL, "签到异常");
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    ToastUtils.show("签到成功");
                    finish();
                    break;
                case UPLOAD_FAIL:
                    ToastUtils.show(msg.obj.toString());
                    break;
                case UPLOAD_SUCCESS1:
                    ToastUtils.show("提交图片成功");
                    finish();
                    break;
                case UPLOAD_FAIL1:
                    ToastUtils.show("提交图片失败");
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent paramIntent) {

        if (requestCode == 0xa1) {
            Log.d(TAG, "onActivityResult :: requestCode == PHOTO_WITH_CAMERA");
            builder.notifyListeners();

        }
        super.onActivityResult(requestCode, resultCode, paramIntent);
    }

    class UpdateListener implements SignDialog.UpdateCarListener {
        @Override
        public void update() {
        }
    }
}


